package com.z.platform.controller;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 解析congtrollersx.xml文件实现对外提供path和controller的对应关系
 *
 * @author 21051
 */
public class ControllersConfig {

    private Map<String, String> allControllersMap = new HashMap<>();

    /**
     * 使用静态内部类确保对象对外不可见实现单例模式
     */
    private static class inner {
        private static final ControllersConfig CONTROLLERS_CONFIG = new ControllersConfig();
    }

    /**
     * 使用jre自带的 dom解析xml文件到map中
     */
    private ControllersConfig() {
        URL xmlFileUrl = ControllersConfig.class.getClassLoader().getResource("controllers.xml");
        File xmlFile = null;
        if (null != xmlFileUrl) {
            xmlFile = new File(xmlFileUrl.getFile());
        }
        //建立DocumentBuilderFactor，用于获得DocumentBuilder对象：
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //2.建立DocumentBuidler：
        DocumentBuilder builder = null;
        try {
            builder = factory.newDocumentBuilder();
            //3.建立Document对象，获取树的入口：
            Document doc = builder.parse(xmlFile);
            //4.建立NodeList：
            NodeList nodeList = doc.getElementsByTagName("controller");
            //5.进行xml信息获取
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                NamedNodeMap namedNodeMap = node.getAttributes();
                String path = namedNodeMap.getNamedItem("path").getNodeValue();
                String aClass = namedNodeMap.getNamedItem("class").getNodeValue();
                allControllersMap.put(path, aClass);
            }
        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }
    }

    public static ControllersConfig getInstance() {
        return inner.CONTROLLERS_CONFIG;
    }


    public String getControllersNameByPath(String path) {
        return allControllersMap.get(path);
    }
}
